package org.ffmmx.gxhotel.inteceptor;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.ffmmx.common.util.TokenUtil;
import org.ffmmx.gxhotel.common.WithLog;
import org.ffmmx.gxhotel.model.Result;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 令牌验证拦截器
 */
public class TokenValidatorInterceptor implements HandlerInterceptor, WithLog{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        Boolean tokenValidateResult = false;
        String token = request.getParameter("token");
        try {
            if (StringUtils.isEmpty(token)) {
                throw new RuntimeException("令牌为空");
            }
            tokenValidateResult = TokenUtil.validateToken(token);
            if (!tokenValidateResult) {
                throw new RuntimeException("令牌不正确,可能已经过期了,尝试重新登录");
            }
        } catch (RuntimeException e) {
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Result<Object> result=new Result<>();
            result.setMsg(e.getMessage());
            if (logger().isDebugEnabled()) {
                result.setException(e);
            }
            result.setSuccess(false);
            result.setCode(0);

            ServletOutputStream out = response.getOutputStream();
            ObjectMapper mapper=new ObjectMapper();
            JsonGenerator jsonGenerator = mapper.getFactory().createGenerator(out);
            jsonGenerator.writeObject(result);
            out.close();
        }

        return tokenValidateResult;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

    }
}
